﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Net;
using seo.Buz;
using seo.Data;
using seo.util;

namespace seo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        CookieContainer CookieJar = new CookieContainer();

        //my vars
        HttpWebResponse HttpWResponse;
        HttpHelper httpHelper = new HttpHelper();
        List<string> urlList = null;

        private void btnDo_Click(object sender, EventArgs e)
        {
            HtmlAnalyzer ha = new HtmlAnalyzer();
            urlList = ha.getUrlList(rtbResult.Text);
            rtbResult.Text = ha.getUrlsFromHtml(rtbResult.Text);
            rtbResult.Text = ha.getUrlString(rtbResult.Text);
        }

        bool MakeWebRequest(Uri URL, string Method)
        {
            // this function will try to make a connection and then fill out the 
            // different controls with their correct values based on the request
            // it will return a false if it fails.

            // declare a WebProxy class object to use.

            //try catch block to catch any errors
            try
            {
    
                //Create a new request
                HttpWebRequest HttpWRequest = (HttpWebRequest)WebRequest.Create(URL);
                // set the HttpWebRequest objects cookie container
                // if you have any cookies that you want to go with the request you can add them 
                // to the cookiecontainer. If you had made a previous request that returned any cookies
                // that needed to be sent on subsequent request this will make sure that they are sent. 
                HttpWRequest.CookieContainer = CookieJar;
                

                // the default credentials are usually the Windows credentials (user name, password, and domain) of the user running the application                    
                HttpWRequest.Credentials = CredentialCache.DefaultCredentials;

                // set the name of the user agent. This is the client name that is passed to IIS
               // HttpWRequest.UserAgent = "CSharp HTTP Sample";
                // set the connection keep-alive
                HttpWRequest.KeepAlive = true; //this is the default
                //we don't want caching to take place so we need
                // to set the pragma header to say we don't want caching
                HttpWRequest.Headers.Set("Pragma", "no-cache");
                //set the request timeout to 5 min.
                HttpWRequest.Timeout = 300000;
                // set the request method
                HttpWRequest.Method = Method;
   

                //check to see if we have previously created a response object
                if (null != HttpWResponse)
                {
                    HttpWResponse.Close(); // close any previous connection
                    HttpWResponse = null; // clear the object. 
                }
                //get the response. This is where we make the connection to the server
                HttpWResponse = (HttpWebResponse)HttpWRequest.GetResponse();

                // Get the Status code
                int iStatCode = (int)HttpWResponse.StatusCode;
 
                return true;
            }
            catch (WebException WebExcp)
            {
                MessageBox.Show(WebExcp.Message.ToString());
                ICertificatePolicy CertPolicy = ServicePointManager.CertificatePolicy;

                return false;
            }
            catch (Exception e) // get any other error
            {
                MessageBox.Show(e.Message.ToString());
                return false;
            }

        }

        private void btnSendRequest_Click(object sender, EventArgs e)
        {
            //this is where we will send the selected request for the URL specifided
            //string sRequestType = "GET"; //default is GET
            string sURL = txtURL.Text;
            ////http://www.google.com/search?q=trip&hl=en&biw=1276&bih=616&prmd=n&start=90&sa=N
            sURL = sURL + "search?q="+ txtKeyWords.Text.Trim() +"&hl=en&biw=1276&bih=616&prmd=n&start="+ 100 +"&sa=N";
            //string result = httpHelper.sendRequest(sURL);
            string result = GoogleSearch.Search(txtKeyWords.Text.ToString(), 100);
            rtbResult.Text = result;
            return;
            /*
            Uri requestURL;

              //to do parse the URL to see if it has http or https if the in it
                //MessageBox.Show(sURL);
            string temp = sURL.ToLower();
            
            try
            {
                 requestURL = new Uri(sURL);
            }
            catch (UriFormatException UriExcp)
            {
                 MessageBox.Show(UriExcp.Message.ToString());
                 return;
            }
         
     
            //Call a function that does the work to get the request.
            if (!MakeWebRequest(requestURL, sRequestType))
            {
                return; // the call failed
            }

            //we want to enable and disable some buttons.

            StreamReader sr = new StreamReader(HttpWResponse.GetResponseStream(), Encoding.ASCII);
            //Convert the stream to a string
            string s = sr.ReadToEnd();
            sr.Close();
            rtbResult.Text = s; /**/

        }

        private void btnArticle_Click(object sender, EventArgs e)
        {
            HtmlAnalyzer ha = new HtmlAnalyzer();
            //rtbResult.Text = ha.getArticleFromHtml(rtbResult.Text, txtKeyWords.Text);
            //rtbResult.Text = ha.deleteHtml(rtbResult.Text);

            if (urlList != null && urlList.Count > 0)
            {
                string url = urlList[0];
                string html = httpHelper.sendRequest(url);
                rtbResult.Text = ha.deleteHtml(html);
            }
            else
            {
                string url = rtbResult.Text;
                string html = httpHelper.sendRequest(url);
                rtbResult.Text = ha.deleteHtml(html);
            }
        }

        private void btnTranslate_Click(object sender, EventArgs e)
        {
            //rtbResult.Text = GoogleTranslate.Translate(rtbResult.Text, "en", "zh-CN");
            rtbResult.Text = GoogleTranslate.Translate(rtbResult.Text, "zh-CN", "en");
            BlackHat bh = new BlackHat();
            //rtbResult.Text = bh.RemoveUselessString(rtbResult.Text);
        }

        private void btnBlackHat_Click(object sender, EventArgs e)
        {
            KeywordBuz keywordBuz = new KeywordBuz();
            WebSiteBuz websiteBuz = new WebSiteBuz();
            List<Keyword> keywordList = keywordBuz.getAllKeyword();
            if (keywordList != null)
            {
                for (int i = 0; i < 3; i++)
                {
                    foreach (Keyword key in keywordList)
                    {
                        Website website = websiteBuz.getWebsiteById(key.siteid);
                        if (website != null)
                        {
                            BlackHat blackHat = new BlackHat(website, key);
                            blackHat.Excute();
                        }
                    }
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            GetContent getContent = new GetContent();

            // string html = GoogleSearch.Search("trip", 10);
            //string html = httpHelper.sendRequest(rtbResult.Text);
            string html = rtbResult.Text;
            /*
            List<string> urlList = null;
            HtmlAnalyzer ha = new HtmlAnalyzer();
            urlList = ha.getUrlList(html);
            if (urlList != null && urlList.Count > 0)
            {
                string url = urlList[0];
                html = httpHelper.sendRequest(url);
                //article = ha.deleteHtml(html);
                
            }            
            */
            txtKeyWords.Text = getContent.getTitle(html);
            HtmlAnalyzer ha = new HtmlAnalyzer();
            html = getContent.getContentUsingParser(html);
            //html = ha.deleteHtml(html);
            html = html.Substring(0, html.LastIndexOf("\n"));//去掉yi-look文章最后一段版权说明
            this.rtbResult.Text = html;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string html = httpHelper.sendRequest(rtbResult.Text);
            rtbResult.Text = html;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            BlackHat bh = new BlackHat();
            rtbResult.Text = bh.FilterArticle(rtbResult.Text);
        }

        private void button4_Click(object sender, EventArgs e)
        {
            string html = rtbResult.Text;
            HomeUrlGetter getter = new HomeUrlGetter();
            List<string> list = getter.GetAllUrlFromHtml(html);
            string urlStr = String.Empty;
            foreach (string url in list)
            {
                urlStr += url + "\n";
            }
            rtbResult.Text = urlStr;
        }

        private void button5_Click(object sender, EventArgs e)
        {
            YiLookCollector collector = new YiLookCollector();
           // collector.collectArtsFromPage(1);
        }
    }
 
}
